<template>
  <el-card v-show="isShowList === 2">
    <el-form ref="skuForm" :model="skuForm" :rules="rules" label-width="80px">
      <el-form-item label="SPU名称">
        {{ spu.spuName }}
      </el-form-item>
      <!--

        price: "",
        skuAttrValueList: [],
        skuDefaultImg: "",
        skuDesc: "",
        skuName: "",
        skuSaleAttrValueList: [],
        tmId: "",
        weight: "",
       -->
      <el-form-item label="SKU名称" prop="skuName">
        <el-input
          v-model="skuForm.skuName"
          placeholder="请输入SKU名称"
        />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number
          v-model="skuForm.price"
          class="input-number"
          controls-position="right"
          placeholder="请输入价格"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="重量" prop="weight">
        <el-input-number
          v-model="skuForm.weight"
          class="input-number"
          controls-position="right"
          placeholder="请输入重量"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="SKU描述" prop="skuDesc">
        <el-input
          v-model="skuForm.skuDesc"
          type="textarea"
          :row="3"
          placeholder="请输入SKU描述"
        />
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row>
          <el-col
            v-for="(skuAttrValue, index) in skuAttrValueList"
            :key="skuAttrValue.id"
            :xs="{ span: 24 }"
            :sm="{ span: 12 }"
            :lg="{ span: 8 }"
          >
            <el-form-item :label="skuAttrValue.attrName">
              <el-select v-model="skuForm.skuAttrValueList[index]">
                <el-option
                  v-for="attrValue in skuAttrValue.attrValueList"
                  :key="attrValue.id"
                  :value="`${skuAttrValue.id}:${skuAttrValue.attrName}:${attrValue.id}:${attrValue.valueName}`"
                  :label="attrValue.valueName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row>
          <el-col
            v-for="(skuSaleAttrValue, index) in skuSaleAttrValueList"
            :key="skuSaleAttrValue.id"
            :xs="{ span: 24 }"
            :sm="{ span: 12 }"
            :lg="{ span: 8 }"
          >
            <el-form-item :label="skuSaleAttrValue.saleAttrName">
              <el-select v-model="skuForm.skuSaleAttrValueList[index]">
                <el-option
                  v-for="spuSaleAttrValue in skuSaleAttrValue.spuSaleAttrValueList"
                  :key="spuSaleAttrValue.id"
                  :value="`${skuSaleAttrValue.id}:${skuSaleAttrValue.saleAttrName}:${spuSaleAttrValue.id}:${spuSaleAttrValue.saleAttrValueName}`"
                  :label="spuSaleAttrValue.saleAttrValueName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuDefaultImg">
        <el-table
          class="spu-table"
          :data="skuImageList"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img
                style="width: 100px; height: 100px"
                :src="row.imgUrl"
                :alt="row.imgName"
              >
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName" />
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-button
                v-show="!row.isDefault"
                type="primary"
                size="mini"
                @click="setDefaultImg($index)"
              >设置默认图片</el-button>
              <el-button
                v-show="row.isDefault"
                type="success"
                size="mini"
                disabled
              >默认图片</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addSku">确认</el-button>
        <el-button @click="resetData">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { mapState } from 'vuex'
import { reqGetAttrList } from '@api/attr'
import { reqGetSpuSaleAttrList, reqGetSpuImageList } from '@api/spu'
import { reqAddSku } from '@api/sku'

export default {
  name: 'AddSku',
  props: ['isShowList'],
  data() {
    /*
      {
  "category3Id": 0,
  "createTime": "2021-03-24T05:44:30.646Z",
  "id": 0,
  "isSale": 0,
  "price": 0,
  "skuAttrValueList": [
    {
      "attrId": 0,
      "attrName": "string",
      "id": 0,
      "skuId": 0,
      "valueId": 0,
      "valueName": "string"
    }
  ],
  "skuDefaultImg": "string",
  "skuDesc": "string",
  "skuImageList": [
    {
      "id": 0,
      "imgName": "string",
      "imgUrl": "string",
      "isDefault": "string",
      "skuId": 0,
      "spuImgId": 0
    }
  ],
  "skuName": "string",
  "skuSaleAttrValueList": [
    {
      "id": 0,
      "saleAttrId": 0,
      "saleAttrName": "string",
      "saleAttrValueId": 0,
      "saleAttrValueName": "string",
      "skuId": 0,
      "spuId": 0
    }
  ],
  "spuId": 0,
  "tmId": 0,
  "weight": "string"
}
    */
    return {
      spu: {},
      skuForm: {
        price: '',
        skuAttrValueList: [], // 收集的平台属性
        skuDefaultImg: '',
        skuDesc: '',
        skuName: '',
        skuSaleAttrValueList: [], // 收集的销售属性
        tmId: '',
        weight: '',
        skuImageList: [] // 收集的
      },
      skuAttrValueList: [], // 请求回来的平台属性
      skuSaleAttrValueList: [], // 请求回来的销售属性
      skuImageList: [],
      rules: {
        price: [{ required: true, message: '请输入值', trigger: 'blur' }],
        skuName: [{ required: true, message: '请输入值', trigger: 'blur' }],
        skuDesc: [{ required: true, message: '请输入值', trigger: 'blur' }],
        weight: [{ required: true, message: '请输入值', trigger: 'blur' }],
        skuSaleAttrValueList: [{ required: true, validator: this.validator }],
        skuAttrValueList: [{ required: true, validator: this.validator }],
        skuDefaultImg: [{ required: true, validator: this.imgValidator }]
      }
    }
  },
  computed: {
    ...mapState({
      // 选中的分类id
      category1Id: (state) => state.category.category1Id,
      category2Id: (state) => state.category.category2Id,
      category3Id: (state) => state.category.category3Id
    })
  },
  mounted() {
    this.$bus.$on('receiveSpuDataToSku', this.receiveSpuDataToSku)

    // 测试
    // this.receiveSpuDataToSku({});
  },
  methods: {
    handleSelectionChange(val) {
      this.skuForm.skuImageList = val
    },
    imgValidator(rule, value, callback) {
      const isSelected = this.skuImageList.some((img) => img.isDefault)
      if (!isSelected) {
        callback('请选择一张默认图片')
        return
      }

      const length = this.skuForm.skuImageList.length
      if (!length) {
        callback('请选择至少一张图片')
        return
      }

      callback()
    },
    setDefaultImg(index) {
      this.skuImageList.forEach((img) => {
        img.isDefault = false
      })
      this.skuImageList[index].isDefault = true
      // 清空校验
      this.$refs.skuForm.clearValidate(['skuDefaultImg'])
    },
    addSku() {
      this.$refs.skuForm.validate(async(status) => {
        // console.log(status);
        if (status) {
          const {
            category3Id,
            skuForm: {
              price,
              skuAttrValueList,
              skuImageList,
              skuDesc,
              skuName,
              skuSaleAttrValueList,
              tmId,
              weight
            },
            spu
          } = this

          await reqAddSku({
            category3Id,
            price,
            skuAttrValueList: skuAttrValueList.map((item) => {
              const [attrId, attrName, valueId, valueName] = item.split(':')
              return {
                attrId,
                attrName,
                valueId,
                valueName
              }
            }),
            skuDefaultImg: skuImageList.find((img) => img.isDefault).imgUrl,
            skuDesc,
            skuImageList: skuImageList.map((item) => {
              return {
                ...item,
                isDefault: item.isDefault ? '1' : '0'
              }
            }),
            skuName,
            skuSaleAttrValueList: skuSaleAttrValueList.map((item) => {
              const [
                saleAttrId,
                saleAttrName,
                saleAttrValueId,
                saleAttrValueName
              ] = item.split(':')

              return {
                saleAttrId,
                saleAttrName,
                saleAttrValueId,
                saleAttrValueName
              }
            }),
            spuId: spu.id,
            tmId,
            weight
          })

          this.$message.success('添加SKU成功')
          this.resetData()
        }
      })
    },
    resetData() {
      this.spu = {}
      this.skuForm = {
        price: '',
        skuAttrValueList: [], // 收集的平台属性
        skuDefaultImg: '',
        skuDesc: '',
        skuName: '',
        skuSaleAttrValueList: [], // 收集的销售属性
        tmId: '',
        weight: '',
        skuImageList: [] // 收集的
      }
      this.skuAttrValueList = [] // 请求回来的平台属性
      this.skuSaleAttrValueList = [] // 请求回来的销售属性
      this.skuImageList = []

      this.$emit('update:isShowList', 0)
      this.$refs.skuForm.clearValidate()
    },
    validator(rule, value, callback) {
      // 校验的字段名称
      const name = rule.field

      value = value.filter(Boolean)

      if (value.length === this[name].length) {
        callback()
        return
      }

      callback('所有选项都是必填项')
    },
    receiveSpuDataToSku(spu) {
      this.spu = spu

      Promise.all([
        reqGetAttrList({
          category1Id: this.category1Id,
          category2Id: this.category2Id,
          category3Id: this.category3Id

          // 测试
          // category1Id: 1,
          // category2Id: 5,
          // category3Id: 20,
        }),

        reqGetSpuSaleAttrList(spu.id),
        reqGetSpuImageList(spu.id)
        // 测试
        // reqGetSpuSaleAttrList(1213),
        // reqGetSpuImageList(1213),
      ])
        .then((res) => {
          this.skuAttrValueList = res[0].data
          this.skuSaleAttrValueList = res[1].data
          this.skuImageList = res[2].data.map((img) => {
            return {
              ...img,
              isDefault: false
            }
          })
        })
        .catch(() => {
          this.$message.error('获取数据失败~')
        })
    }
  }
}
</script>

<style lang="sass" scoped>
.input-number
  width: 100%
</style>
